package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.AudioState;
import com.zhiqianbao.entity.CreditRating;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserInfo;
import com.zhiqianbao.shared.SharedPreferanceUtils;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.FileUtils;
import com.zhiqianbao.utils.HttpUtils;
import com.zhiqianbao.utils.WorthPurseUtil;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.trinea.android.common.util.StringUtils;

/**
 * Created by Administrator on 2015/12/22.
 */
public class SettingActivity extends BaseActivity {
    public static final int DATA_FAILED=0x123;
    public static final int DATA_SCUESSFUL=0x124;
    private Gson gson = new Gson();
    /**o
     * 信用等级
     */
    TextView tvQqualityRating;
    private static final int JUMPTO_UPDATE_BANKCARD = 110310421;
    /**
     * 身份证信息
     */
    RelativeLayout relativeLayoutSetIDCardMessage;

    //填写资料
    Button bt_message;
    /**
     * 持证拍照信息
     */
    RelativeLayout relativeLayoutSetChiIDCardPhoneMessage;
    /**
     * 银行卡信息
     */
    RelativeLayout relativeLayoutSetBankCardMessage;
    /**
     * 工作信息
     */
    RelativeLayout relativeLayoutSetJobInfo;
    /**
     * 联系人信息
     */
    RelativeLayout relativeLayoutSetHouseholdContacts;

    /**
     * 补充附件
     */
    RelativeLayout relativeLayoutSetAdjunctMessage;
    SharedPreferanceUtils sharedPreferanceUtils;
    /**
     * 优惠券
     */
    RelativeLayout relativeLayoutSetMycoupon;

    /**
     * 更改密码
     */
    RelativeLayout relativeLayoutSetChangeLoginPass;
    /**
     * 更改手机号
     */
    RelativeLayout relativeLayoutSetChangePhone;
    private String emergency;
    private String jobState;
    private String telecon1;
    private String idCard;
    /**
     * 历史申请记录
     */
    RelativeLayout relativeLayoutApplicationHistoryRecords;
    /**
     * 姓名
     */
    TextView textViewLineOfNameContent;
    private String telecon;
    private String taoBao;

    private String job_state;
    private String identity_state;
    private String telecom_state;
    private String taobao_state;
    private String emergency_contact_state;
    /**
     * 退出登录
     */
    Button buttonSetOut;

    CreditRating creditRating;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_OK:
                    CreditRating creditRating = (CreditRating) msg.obj;
                    CreditRating.deleteAll(CreditRating.class);
                    creditRating.save();
                    tvQqualityRating.setText(creditRating.getName());
                    break;
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
            }
        }
    };

    Handler logoutHanlder = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    buttonSetOut.setEnabled(true);
                    break;
                case RESULT_OK:
                    buttonSetOut.setEnabled(true);
                    Result data = (Result) msg.obj;
                    if (data != null) {
                        if (data.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            exitLoginClearUserMsg("-1");
                        } else {
                            showShortToast1(data.getMsg());
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void
    onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        init();
        initView();
//        addListner();
        if (Constants.LOGIN_USER!=null){
            initData();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (Constants.LOGIN_USER!=null){
            initData();
        }
    }

    private void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message message = new Message();
                Map<String, String> mapParams = new HashMap<>();
                mapParams.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                mapParams.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/auth/authState",
                        mapParams, SettingActivity.this);
                if (StringUtils.isBlank(result)) {
                    message.what = DATA_FAILED;
                } else {
                    message.what = DATA_SCUESSFUL;
                    AudioState data =gson.fromJson(result, AudioState.class);
                    message.obj = data;
                }
                postHandler.sendMessage(message);
            }
        }).start();
    }

//    private void addListner() {
//        bt_message.setOnClickListener(this);
//    }

    private void initView() {
         sharedPreferanceUtils = new SharedPreferanceUtils(this);
         tvQqualityRating=(TextView)findViewById(R.id.quality_rating_tv);
         relativeLayoutSetIDCardMessage=(RelativeLayout)findViewById(R.id.relativeLayout_set_iDCard_message);
         bt_message=(Button)findViewById(R.id.bt_message);
         relativeLayoutSetChiIDCardPhoneMessage=(RelativeLayout)findViewById(R.id.relativeLayout_set_chi_iDCardPhone_message);
         relativeLayoutSetBankCardMessage=(RelativeLayout)findViewById(R.id.relativeLayout_set_bankCard_message);
         relativeLayoutSetJobInfo=(RelativeLayout)findViewById(R.id.relativeLayout_set_job_info);
         relativeLayoutSetHouseholdContacts=(RelativeLayout)findViewById(R.id.relativeLayout_set_household_contacts);
         relativeLayoutSetAdjunctMessage=(RelativeLayout)findViewById(R.id.relativeLayout_set_adjunct_message);
         relativeLayoutSetMycoupon=(RelativeLayout)findViewById(R.id.relativeLayout_set_mycoupon);
         relativeLayoutSetChangeLoginPass=(RelativeLayout)findViewById(R.id.relativeLayout_set_change_loginPass);
         relativeLayoutSetChangePhone=(RelativeLayout)findViewById(R.id.relativeLayout_set_change_phone);
         relativeLayoutApplicationHistoryRecords=(RelativeLayout)findViewById(R.id.relativeLayout_application_history_records);
         textViewLineOfNameContent=(TextView)findViewById(R.id.textView_line_of_name_content);
         buttonSetOut=(Button)findViewById(R.id.button_set_out);
        try {
            telecon = sharedPreferanceUtils.getTelecon();
            emergency = sharedPreferanceUtils.getEmergency();
            jobState = sharedPreferanceUtils.getJobState();
            taoBao = sharedPreferanceUtils.getTaoBao();
            telecon1 = sharedPreferanceUtils.getTelecon();
            idCard = sharedPreferanceUtils.getidCardState();

            Log.i("出来了12..", telecon + emergency + jobState + taoBao + telecon1 + idCard);
        } catch (Exception e) {

        }

        if (Constants.LOGIN_USER == null) {
            buttonSetOut.setVisibility(View.GONE);
            //没有登录 获取默认数据
            creditRating = new CreditRating();
            creditRating.setYearRate(0.24);
            creditRating.setManageFee(BigDecimal.valueOf(40));
            creditRating.setCreditLine(5000);
            creditRating.setTermLine(6);
            creditRating.setName("HR");

            tvQqualityRating.setText(creditRating.getName());
            textViewLineOfNameContent.setText("未登录");
        } else {
            buttonSetOut.setVisibility(View.GONE);
            // 取出用户的额度 和 信用等级
            List<CreditRating> creditRatings = CreditRating.find(CreditRating.class, null, new String[]{});
            if (creditRatings.isEmpty()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String creditRatingId =Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getCreditRatingId().toString(): "";
                        Map<String, String> param = new HashMap<>();
                        param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                        param.put("creditRatingId", creditRatingId);
                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/creditRating", param, SettingActivity.this);
                        Message message = new Message();
                        //请求失败
                        if (StringUtils.isBlank(result)) {
                            message.what = RESULT_CANCELED;
                        } else {
                            Result<CreditRating> data = Result.fromJson(result, CreditRating.class);
                            message.what = RESULT_OK;
                            message.obj = data.getData();
                        }
                        handler.sendMessage(message);
                    }
                }).start();
            } else {
                creditRating = creditRatings.get(0);
                tvQqualityRating.setText(creditRating.getName());
            }
            String userId = Constants.LOGIN_USER.getId().toString();
            List<UserInfo> userInfos = UserInfo.findWithQuery(UserInfo.class, "select * from user_info where user_id = ? ", userId);
            UserInfo userInfo = userInfos.get(0);
            textViewLineOfNameContent.setText(userInfo.getName());
        }
        ButtonClickListener listener = new ButtonClickListener();
        relativeLayoutSetIDCardMessage.setOnClickListener(listener);
        relativeLayoutSetChiIDCardPhoneMessage.setOnClickListener(listener);
        relativeLayoutSetBankCardMessage.setOnClickListener(listener);
        relativeLayoutSetJobInfo.setOnClickListener(listener);
        relativeLayoutSetHouseholdContacts.setOnClickListener(listener);
        relativeLayoutSetAdjunctMessage.setOnClickListener(listener);
        relativeLayoutSetMycoupon.setOnClickListener(listener);
        relativeLayoutSetChangeLoginPass.setOnClickListener(listener);
        relativeLayoutSetChangePhone.setOnClickListener(listener);
        relativeLayoutApplicationHistoryRecords.setOnClickListener(listener);
        buttonSetOut.setOnClickListener(listener);
        bt_message.setOnClickListener(listener);
    }

    @Override
    protected void onRestart() {
        if (Constants.LOGIN_USER == null) {
            buttonSetOut.setVisibility(View.GONE);
            //没有登录 获取默认数据
            creditRating = new CreditRating();
            creditRating.setYearRate(0.24);
            creditRating.setManageFee(BigDecimal.valueOf(40));
            creditRating.setCreditLine(5000);
            creditRating.setTermLine(6);
            creditRating.setName("HR");

            tvQqualityRating.setText(creditRating.getName());
            textViewLineOfNameContent.setText("未登录");
        } else {
            buttonSetOut.setVisibility(View.GONE);
            // 取出用户的额度 和 信用等级
            List<CreditRating> creditRatings = CreditRating.find(CreditRating.class, null, new String[]{});
            if (creditRatings.isEmpty()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String creditRatingId =Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getCreditRatingId().toString(): "";
                        Map<String, String> param = new HashMap<>();
                        param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                        param.put("creditRatingId", creditRatingId);
                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/creditRating", param, SettingActivity.this);
                        Message message = new Message();
                        //请求失败
                        if (StringUtils.isBlank(result)) {
                            message.what = RESULT_CANCELED;
                        } else {
                            Result<CreditRating> data = Result.fromJson(result, CreditRating.class);
                            message.what = RESULT_OK;
                            message.obj = data.getData();
                        }
                        handler.sendMessage(message);
                    }
                }).start();
            } else {
                creditRating = creditRatings.get(0);
                tvQqualityRating.setText(creditRating.getName());
                String userId = Constants.LOGIN_USER.getId().toString();
                List<UserInfo> userInfos = UserInfo.findWithQuery(UserInfo.class, "select * from user_info where user_id = ? ", userId);
                UserInfo userInfo = userInfos.get(0);
                textViewLineOfNameContent.setText(userInfo.getName());
            }
        }
        super.onRestart();
    }


    class ButtonClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
                if(R.id.bt_message==v.getId()) {
                    //流程主页面
                    if (Constants.LOGIN_USER != null) {
                        startActivityForResult(new Intent(SettingActivity.this, ProcessActivity.class), 3);
                    } else {
                        startActivity(new Intent(SettingActivity.this,
                                WorthPurseUtil.getZhiddActivity().getClass()));
                        finish();
                    }
                }
                else if(R.id.relativeLayout_set_iDCard_message==v.getId()) {
                    //身份证信息
                    if (Constants.LOGIN_USER != null) {
                        if (!TextUtils.isEmpty(identity_state)) {
                            if ("1".equals(identity_state) || "2".equals(identity_state)) {
                                startActivity(new Intent(SettingActivity.this, IdCardMessageActivity.class));
                            } else {
                                showAlertMsgDialog1("请完善资料后进行借款", "确认", "取消");
//                                startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
                            }
                        } else {
//                            startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
                        }
                    } else {
                        startActivity(new Intent(SettingActivity.this,
                             WorthPurseUtil.getZhiddActivity().getClass()));
                        finish();
                    }
                }
                else if(R.id.relativeLayout_set_chi_iDCardPhone_message==v.getId()) {
                    //持证拍照信息
                    if (Constants.LOGIN_USER != null) {
                        if (!TextUtils.isEmpty(identity_state)) {
                            if ("1".equals(identity_state) || "2".equals(identity_state)) {
                                startActivity(new Intent(SettingActivity.this, TakeIdCardMakePicActivity.class));
                            } else {
                                showAlertMsgDialog1("请完善资料后进行借款", "确认", "取消");
//                                startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
                            }
                        } else {
//                        startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
                        }
                    } else {
                        startActivity(new Intent(SettingActivity.this,
                            WorthPurseUtil.getZhiddActivity().getClass()));
                        finish();
                    }
                }
                else if(R.id.relativeLayout_set_bankCard_message==v.getId()) {
                    //银行卡信息
                    if (Constants.LOGIN_USER != null) {
                        if (!TextUtils.isEmpty(identity_state) && !TextUtils.isEmpty(emergency_contact_state) && !TextUtils.isEmpty(job_state)) {
                            if (("1".equals(identity_state) || "2".equals(identity_state)) && ("1".equals(emergency_contact_state) || "2".equals(emergency_contact_state))) {
//                            CheckUtils.checkUserState(SettingActivity.this, BankCardInfoActivity.class);
                                startActivity(new Intent(SettingActivity.this, BankCardInfoActivity.class));
                            } else {
                                showAlertMsgDialog1("请完善资料后进行借款", "确认", "取消");
//                            startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
                            }
                        } else {
//                        startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
//                        showAlertMsgDialog1("请完善资料后进行借款", "确认", "取消");
//                        startActivity(new Intent(SettingActivity.this, BankCardInfoActivity.class));
                        }
                    } else {
                        startActivity(new Intent(SettingActivity.this,
                            WorthPurseUtil.getZhiddActivity().getClass()));
                        finish();
                    }
                }
                else if(R.id.relativeLayout_set_job_info==v.getId()) {
                    //工作信息
                        if (Constants.LOGIN_USER != null) {
                            if (!TextUtils.isEmpty(job_state)) {
                                if ("1".equals(job_state) || "2".equals(job_state)) {
                                    startActivity(new Intent(SettingActivity.this, JobInfoActivity.class));
                                } else {
                                    showAlertMsgDialog1("请完善资料后进行借款", "确认", "取消");
                                }
                            } else {

                            }
                        } else {
                            startActivity(new Intent(SettingActivity.this,
                                WorthPurseUtil.getZhiddActivity().getClass()));
                            finish();
                        }
                }
                else if(R.id.relativeLayout_set_household_contacts==v.getId()) {
                    //联系人信息

                        if (Constants.LOGIN_USER != null) {
                            if (!TextUtils.isEmpty(emergency_contact_state)) {
                                if ("1".equals(emergency_contact_state) || "2".equals(emergency_contact_state)) {
                                    startActivity(new Intent(SettingActivity.this, ContactInfo1Activity.class));
                                } else {
                                    showAlertMsgDialog1("请完善资料后进行借款", "确认", "取消");
//                                startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
                                }
                            } else {
//                        startActivity(new Intent(SettingActivity.this,ProcessActivity.class));
                            }
                        } else {
                            startActivity(new Intent(SettingActivity.this,
                               WorthPurseUtil.getZhiddActivity().getClass()));
                            finish();
                        }

                }
                else if(R.id.relativeLayout_set_adjunct_message==v.getId()) {
                    //补充附件
                        if (Constants.LOGIN_USER != null) {
                            startActivity(new Intent(SettingActivity.this, AttachmentListActivity.class));
                        } else {
                            startActivity(new Intent(SettingActivity.this,
                               WorthPurseUtil.getZhiddActivity().getClass()));
                            finish();
                        }
                }
                else if(R.id.relativeLayout_set_mycoupon==v.getId()) {
                    //优惠券
                    if (Constants.LOGIN_USER != null) {
                        Intent intent = new Intent(SettingActivity.this, MyCouponActivity.class);
                        intent.putExtra("serviceType", "1");
                        startActivity(intent);
                    } else {
                        startActivity(new Intent(SettingActivity.this,
                           WorthPurseUtil.getZhiddActivity().getClass()));
                        finish();
                    }
                }
                else if(R.id.relativeLayout_set_change_loginPass==v.getId()) {
                    //更改密码
                        if (Constants.LOGIN_USER == null) {
                            Intent loginIntent = new Intent(SettingActivity.this,
                              WorthPurseUtil.getZhiddActivity().getClass());
                            startActivity(loginIntent);
                            finish();
                        } else {
                            Intent changePassword = new Intent(SettingActivity.this, ChangePasswordActivity.class);
                            startActivity(changePassword);
                        }
                }
                else if(R.id.relativeLayout_set_change_phone==v.getId()) {
                    //手机号码
                        //CheckUtils.checkUserState(SettingActivity.this, ChangePhoneActivity.class);
                        if (Constants.LOGIN_USER == null) {
                            Intent loginIntent = new Intent(SettingActivity.this,
                               WorthPurseUtil.getZhiddActivity().getClass());
                            startActivity(loginIntent);
                            finish();
                        } else {
                            Intent changePhone = new Intent(SettingActivity.this, ChangePhoneActivity.class);
                            startActivity(changePhone);
                        }
                }
                else if(R.id.relativeLayout_application_history_records==v.getId()) {
                    //历史申请记录
                        if (Constants.LOGIN_USER != null) {
                            startActivity(new Intent(SettingActivity.this, ApplyRecordHistoryActivity.class));
                        } else {
                            startActivity(new Intent(SettingActivity.this,
                               WorthPurseUtil.getZhiddActivity().getClass()));
                            finish();
                        }
                }
                else if(R.id.button_set_out==v.getId()) {
                //退出登录
                    buttonSetOut.setEnabled(false);
                    if (Constants.LOGIN_USER != null) {
                        if (!TextUtils.isEmpty(Constants.LOGIN_USER.getId() + "")) {
                            //请求退出接口
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    Message message = new Message();
                                    Map<String, String> param = new HashMap<>();
                                    param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                                    param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");

                                    String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/logout", param, SettingActivity.this);
                                    if (StringUtils.isBlank(result)) {
                                        message.what = RESULT_CANCELED;
                                    } else {
                                        Result data = Result.fromJson(result, HashMap.class);
                                        message.obj = data;
                                        message.what = RESULT_OK;
                                    }
                                    logoutHanlder.sendMessage(message);
                                }
                            }).start();
                        }
                    }
            }
        }
    }
    long mExitTime;
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                mExitTime = System.currentTimeMillis();
            } else {
                Intent mHomeIntent = new Intent(Intent.ACTION_MAIN);
                mHomeIntent.addCategory(Intent.CATEGORY_HOME);
                mHomeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                startActivity(mHomeIntent);
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void exitLoginClearUserMsg(String selectLogin){
        //退出登录成功
        //清除登录用户缓存
        SharedPreferanceUtils.setClear();
        Constants.LOGIN_USER = null;
        //清除自动登录缓冲内容
        FileUtils.deleteCache("apply.txt");
        FileUtils.deleteCache("user.txt");
        //调到主页面
        Intent intent = new Intent(SettingActivity.this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("tabPosition", 1);
        intent.putExtra("selectLogin", selectLogin);
        startActivity(intent);
        finish();
    }

    Handler postHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_FAILED:
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case DATA_SCUESSFUL:
                    AudioState response = (AudioState) msg.obj;
                    closeWaitDialog();
                    if (response == null) {
                        if (!response.getCode().equals("9")){
                            showShortToast1("网络超时，请再试!");
                        }
//                    closeWaitDialog();
                    }
                    if (response != null) {

                        if (response.getCode().equals("0")) {
//                        closeWaitDialog();
                            try {
                                emergency_contact_state = response.getData().getEmergency_contact_state();
                                identity_state = response.getData().getIdentity_state();
                                job_state = response.getData().getJob_state();
                                taobao_state = response.getData().getTaobao_state();
                                telecom_state = response.getData().getTelecom_state();
                            } catch (Exception e) {

                            }
                        }else if (response.getCode().equals("9")){
                            exitLoginClearUserMsg("9");
                        }
                    }
                    break;
            }

        }
    };
}
